package com.jackiepenghe.huaweimqttlibrary.receivers

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import com.huaweicloud.sdk.iot.device.client.requests.Command
import com.huaweicloud.sdk.iot.device.client.requests.DeviceMessage
import com.huaweicloud.sdk.iot.device.client.requests.PropsSet
import com.huaweicloud.sdk.iot.device.constant.BaseConstant
import com.huaweicloud.sdk.iot.device.constant.IotDeviceIntent
import com.jackiepenghe.huaweimqttlibrary.DebugUtil
import com.jackiepenghe.huaweimqttlibrary.listeners.*


/**
 * MQTT设备连接的通知
 */
class IotDeviceBroadcastReceiver : BroadcastReceiver() {

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 静态声明
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    companion object {
        private val TAG =
            IotDeviceBroadcastReceiver::class.simpleName ?: "IotDeviceBroadcastReceiver"
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 属性声明
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /* * * * * * * * * * * * * * * * * * * 库内部属性 * * * * * * * * * * * * * * * * * * */

    internal var onDeviceConnectListener: OnDeviceConnectListener? = null

    internal var onPropertyReportListener: OnPropertyReportListener? = null

    internal var onDeviceMessageUpListener: OnDeviceMessageUpListener? = null

    internal var onDevicePropertyGetListener: OnDevicePropertyGetListener? = null

    internal var onDevicePropertySetListener: OnDevicePropertySetListener? = null

    internal var onDeviceMessageDownListener: OnDeviceMessageDownListener? = null

    internal var onDeviceCommandListener: OnDeviceCommandListener? = null

    internal var onRespondCommandListener: OnRespondCommandListener? = null

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 实现方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    override fun onReceive(context: Context, intent: Intent) {
        when (intent.action) {
            //设备连接状态
            IotDeviceIntent.ACTION_IOT_DEVICE_CONNECT -> {
                handleDeviceConnect(intent)
            }
            //设备属性上报结果
            IotDeviceIntent.ACTION_IOT_DEVICE_PROPERTIES_REPORT -> {
                handlePropertiesReport(intent)
            }
            //消息上报（上传）结果
            IotDeviceIntent.ACTION_IOT_DEVICE_SYS_MESSAGES_UP -> {
                handleDeviceMessageUp(intent)
            }
            //平台查询设备属性
            IotDeviceIntent.ACTION_IOT_DEVICE_SYS_PROPERTIES_GET -> {
                handleDevicePropertyGet(intent)
            }
            //平台设置设备属性
            IotDeviceIntent.ACTION_IOT_DEVICE_SYS_PROPERTIES_SET -> {
                handleDevicePropertySet(intent)
            }
            //平台消息下发
            IotDeviceIntent.ACTION_IOT_DEVICE_SYS_MESSAGES_DOWN -> {
                handleDeviceMessageDown(intent)
            }
            //平台命令下发
            IotDeviceIntent.ACTION_IOT_DEVICE_SYS_COMMANDS -> {
                handleDeviceCommand(intent)
            }
        }
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 私有方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /**
     * 处理设备连接状态广播
     */
    private fun handleDeviceConnect(intent: Intent) {
        when (intent.getIntExtra(BaseConstant.BROADCAST_STATUS, BaseConstant.STATUS_FAIL)) {
            //设备创建成功
            BaseConstant.STATUS_SUCCESS -> {
                Log.w(TAG, "onReceive: 设备创建成功")
                onDeviceConnectListener?.connectSucceed()
            }

            BaseConstant.STATUS_FAIL -> {
                //设备创建失败
                Log.w(TAG, "onReceive: 设备创建失败")
                //失败原因
                val error = intent.getStringExtra(BaseConstant.COMMON_ERROR) ?: ""
                Log.w(TAG, "onReceive: error $error")
                onDeviceConnectListener?.connectFailed(error)
            }

            BaseConstant.STATUS_LOST -> {
                Log.w(TAG, "onReceive: STATUS_LOST")
                //失败原因
                val error = intent.getStringExtra(BaseConstant.COMMON_ERROR) ?: ""
                Log.w(TAG, "onReceive: error $error")
                onDeviceConnectListener?.disconnect(error)
            }
            BaseConstant.STATUS_RECONNECT ->{
                Log.w(TAG, "onReceive: STATUS_RECONNECT")
                //失败原因
                val error = intent.getStringExtra(BaseConstant.COMMON_ERROR) ?: ""
                Log.w(TAG, "onReceive: error $error")
                onDeviceConnectListener?.reconnect()
            }
        }
    }

    /**
     * 处理设备属性上报结果广播
     */
    private fun handlePropertiesReport(intent: Intent) {
        when (intent.getIntExtra(BaseConstant.BROADCAST_STATUS, BaseConstant.STATUS_FAIL)) {
            BaseConstant.STATUS_SUCCESS -> {
                DebugUtil.logOut(TAG, "上报属性成功!")
                onPropertyReportListener?.reportSucceed()
            }

            BaseConstant.STATUS_FAIL -> {
                val error = intent.getStringExtra(BaseConstant.PROPERTIES_REPORT_ERROR) ?: ""
                DebugUtil.logOut(TAG, "上报属性失败!失败原因：$error\n")
                onPropertyReportListener?.reportFailed(error)
            }
        }
    }

    /**
     * 处理消息上报（上传）结果
     */
    private fun handleDeviceMessageUp(intent: Intent) {
        when (intent.getIntExtra(BaseConstant.BROADCAST_STATUS, BaseConstant.STATUS_FAIL)) {
            BaseConstant.STATUS_SUCCESS -> {
                DebugUtil.logOut(TAG, "消息上报（上传）成功!")
                onDeviceMessageUpListener?.upMessageSucceed()
            }

            BaseConstant.STATUS_FAIL -> {
                val error = intent.getStringExtra(BaseConstant.COMMON_ERROR) ?: ""
                DebugUtil.logOut(TAG, "消息上报（上传）失败!失败原因：$error\n")
                onDeviceMessageUpListener?.upMessageFailed(error)
            }
        }
    }

    /**
     * 处理平台查询设备属性
     */
    private fun handleDevicePropertyGet(intent: Intent) {
        //平台查询设备属性广播携带数据
        val requestId = intent.getStringExtra(BaseConstant.REQUEST_ID) ?: ""
        val serviceId = intent.getStringExtra(BaseConstant.SERVICE_ID) ?: ""
        DebugUtil.logOut(
            TAG,
            "平台查询设备属性: requestId=$requestId,serviceId=$serviceId\n"
        )
        onDevicePropertyGetListener?.onDevicePropertyGet(requestId, serviceId)
    }

    /**
     * 处理平台设置设备属性
     */
    private fun handleDevicePropertySet(intent: Intent) {
        //平台设置设备属性广播携带数据
        val requestId = intent.getStringExtra(BaseConstant.REQUEST_ID) ?: ""
        @Suppress("DEPRECATION") val propsSet: PropsSet? =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                intent.getParcelableExtra(BaseConstant.SYS_PROPERTIES_SET, PropsSet::class.java)
            } else {
                intent.getParcelableExtra(BaseConstant.SYS_PROPERTIES_SET)
            }
        DebugUtil.logOut(
            TAG,
            "平台设置设备属性: requestId=$requestId,propsSet=$propsSet\n"
        )
        onDevicePropertySetListener?.onDevicePropertySet(requestId, propsSet ?: return)
    }

    /**
     * 处理平台消息下发
     */
    private fun handleDeviceMessageDown(intent: Intent) {
        //消息下发广播携带数据
        @Suppress("DEPRECATION") val deviceMessage: DeviceMessage? =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                intent.getParcelableExtra(BaseConstant.SYS_DOWN_MESSAGES, DeviceMessage::class.java)
            } else {
                intent.getParcelableExtra(BaseConstant.SYS_DOWN_MESSAGES)
            }
        DebugUtil.logOut(
            TAG,
            "平台消息下发: deviceMessage=$deviceMessage\n"
        )
        onDeviceMessageDownListener?.onDeviceMessageDownListener(deviceMessage ?: return)
    }

    /**
     * 处理平台命令下发
     */
    private fun handleDeviceCommand(intent: Intent) {
        //命令下发广播携带数据
        val requestId = intent.getStringExtra(BaseConstant.REQUEST_ID) ?: ""
        @Suppress("DEPRECATION") val command: Command? =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                intent.getParcelableExtra(BaseConstant.SYS_COMMANDS, Command::class.java)
            } else {
                intent.getParcelableExtra(BaseConstant.SYS_COMMANDS)
            }
        DebugUtil.logOut(
            TAG,
            "平台命令下发: requestId=$requestId command=${command}\n"
        )
        onDeviceCommandListener?.onDeviceCommand(requestId, command ?: return)
    }
}